package main

import (
	"fmt"
	"github.com/jung-kurt/gofpdf"
	"image"
	"image/jpeg"
	"image/png"
	"os"
	"path/filepath"
)

func main() {
	// 检查参数数量
	if len(os.Args) < 2 || len(os.Args) > 3 {
		fmt.Println("Usage: img2pdf <image_folder_path> [output_pdf_path]")
		return
	}

	// 输入的图片文件夹路径
	imageFolderPath := os.Args[1] // 转换为绝对路径
	absImageFolderPath, err := filepath.Abs(imageFolderPath)
	if err != nil {
		fmt.Printf("Error: Failed to get absolute path for '%s': %v\n", imageFolderPath, err)
		return
	}
	imageFolderPath = absImageFolderPath

	// 输出的 PDF 文件路径
	var outputPdfPath string
	if len(os.Args) == 3 {
		outputPdfPath = os.Args[2]
	} else {
		dirName := filepath.Base(imageFolderPath)
		outputPdfPath = filepath.Join(imageFolderPath, fmt.Sprintf("%s.pdf", dirName))
	}

	// 创建一个新的 PDF 文档
	pdf := gofpdf.New("P", "mm", "A4", "")
	pdf.SetAutoPageBreak(false, 0)

	// 遍历图片文件夹
	var fileList []string
	err = filepath.Walk(imageFolderPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			fmt.Printf("Error: Failed to access file '%s': %v\n", path, err)
			return nil // Continue with the next file
		}
		if !info.IsDir() && (filepath.Ext(path) == ".jpg" || filepath.Ext(path) == ".png") {
			fileList = append(fileList, path)
		}
		return nil
	})
	if err != nil {
		fmt.Printf("Error: Failed to walk through the directory '%s': %v\n", imageFolderPath, err)
		return // Exit the program if there was an error walking through the directory
	}

	for _, filePath := range fileList {
		file, err := os.Open(filePath)
		if err != nil {
			fmt.Printf("Error: Failed to open file '%s': %v\n", filePath, err)
			continue // Skip this file and continue with the next one
		}
		defer file.Close()
		var img image.Image
		if filepath.Ext(filePath) == ".jpg" {
			img, err = jpeg.Decode(file)
		} else if filepath.Ext(filePath) == ".png" {
			img, err = png.Decode(file)
		}
		if err != nil {
			fmt.Printf("Error: Failed to decode image file '%s': %v\n", filePath, err)
			continue // Skip this file and continue with the next one
		}

		// 获取图片的尺寸
		width := float64(img.Bounds().Dx())
		height := float64(img.Bounds().Dy())

		// A4 纸张尺寸
		pageWidth := 210.0
		pageHeight := 297.0

		// 计算缩放比例
		scale := pageWidth / width
		if height*scale > pageHeight {
			scale = pageHeight / height
		}

		// 缩放后的图片尺寸
		newWidth := width * scale
		newHeight := height * scale

		// 将图片添加到 PDF 文档
		pdf.AddPage()
		fmt.Printf("Adding image '%s' to PDF...\n", filePath)
		pdf.Image(filePath, (pageWidth-newWidth)/2, (pageHeight-newHeight)/2, newWidth, newHeight, false, "", 0, "")
	}

	// 保存生成的 PDF 文件
	fmt.Printf("Saving the PDF document to '%s'...\n", outputPdfPath)
	err = pdf.OutputFileAndClose(outputPdfPath)
	if err != nil {
		fmt.Printf("Error: Failed to save PDF document: %v\n", err)
	} else {
		fmt.Println("PDF document saved successfully.")
	}
}
